<template>
  <div>
    <el-row class="warp">
      <!--
        新增博文
            Form 组件提供了表单验证的功能，只需要通过 rule 属性传入约定的验证规则，并 Form-Item 的 prop 属性设置为需校验的字段名即可。具体可以参考官网：http://element.eleme.io/#/zh-CN/component/form
      -->
      <el-col :span="24" class="warp-main">
        <el-form
          ref="infoForm"
          :model="infoForm"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="标题" prop="btitle">
            <el-input v-model="infoForm.btitle"></el-input>
          </el-form-item>

          <!-- <el-form-item label="分类" prop="bcategory">
            <el-input v-model="infoForm.bcategory"></el-input>
          </el-form-item> -->
          
          <el-form-item label="分类" prop="bcategory">
            <el-select v-model="thisbcategory" filterable clearable>
              <el-option
                v-for="item in blogNodeinfoForm"
                :key="item.bID"
                :label="item.btitle"
                :value="item.btitle"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="作者" prop="bsubmitter">
            <el-input v-model="infoForm.bsubmitter"></el-input>
          </el-form-item>

          <!-- 这里开始新建 -->
          <el-form-item label="父导航" prop="bparentId">
            <el-select
              v-model="boxFather.btitle"
              filterable
              clearable
              @visible-change="handleSelectVisibleChange"
              @change="handleSelectChange"
            >
              <el-option
                v-for="item in blogFatherinfoForm"
                :key="item.bID"
                :label="item.btitle"
                :value="item.btitle"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="多级页归属" prop="bparentId" v-if="bottomflage&&(thisbcategory === '解决方案'|| bnodeLevel>=4)">
            <el-select
              v-model="bottomNodeData.btitle"
              filterable
              clearable
              @visible-change="handleSelectVisibleChange_BottomNode"
              @change="handleSelectChange_BottomNode"
            >
              <el-option
                v-for="item in bottomNodeForm"
                :key="item.bID"
                :label="item.btitle"
                :value="item.btitle"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="节点等级" prop="bnodeLevel">
            <el-input v-model="infoForm.bnodeLevel" type="number"></el-input>
          </el-form-item>

          <el-form-item label="推荐等级" prop="bstarLevel">
            <el-input v-model="infoForm.bstarLevel" type="number"></el-input>
          </el-form-item>

          <el-form-item label="备注简介" prop="bRemark">
            <el-input v-model="infoForm.bRemark"></el-input>
          </el-form-item>

          <el-form-item label="相关推荐" prop="StarList">
            <el-select
              v-model="newstarlist"
              multiple
              filterable
              @visible-change="handleSelectStart"
            >
              <el-option
                v-for="item in blogFatherinfoForm"
                :key="item.bID"
                :label="item.btitle"
                :value="item.bID"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 展示已上传图片 -->
          <el-form-item label="展示图" prop="bimage">
            <el-upload
              class="upload-demo"
              action="/images/Upload/Pic"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              multiple
            >
              <div class="upload-list">
                <!-- 循环展示已上传的图片 -->
                <div
                  v-for="(image, index) in images"
                  :key="index"
                  class="image-item"
                >
                  <img :src="image.ImagePath" class="avatar" />
                  <p>{{ images.ImagePath }}</p>
                  <span class="delete-icon" @click.stop="deleteImage(index)"
                    >X</span
                  >
                  <!-- 点击删除图片 -->
                </div>
              </div>
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="拖放上传文件夹" prop="folderUpload">
            <el-upload
    class="upload-demo"
    :action="uploadAction"
    :show-file-list="false"
    :on-success="handleFolderUploadSuccess"
    :before-upload="beforeFolderUpload"
    :on-drop="handleDrop"
    multiple
    directory
    :data="uploadData"
    drag
  >
    <i class="el-icon-upload2"></i>
    <div class="el-upload__text">将文件夹拖到此处上传</div>
  </el-upload>
  
</el-form-item>
       

          <div>
            <!-- <EditorComponent /> -->
            <EditorComponent
              ref="editorComponent"
              :initialValue="this.initialValue"
            ></EditorComponent>
          </div>

          <el-form-item>
            <el-button type="primary" :disabled="submitting" @click="onSubmit"
              >{{buttonSubit}}</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>

</template>

<script>
// require styles
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import EditorComponent from "./EditorComponent.vue"; //调用编辑器
import {
  addBlog,
  getBlogDeatil,
  editBlog,
  UpdateProductList,
  GetSubBlog,
  DelBlogImages,
  GetBlogNode,
} from "../../api/api";

export default {
  data() {
    return {
      uploadAction: '/api/Blog/UploadLanHu', // 上传接口的URL
      uploadData: {}, // 上传时附带的数据
      bottomflage:false,
      bottomNodeForm:[],
      bottomNodeData:{},
      buttonSubit:"提交按钮",
      initialValue: "",
      submitting: false,
      id: this.$route.params.id,
      infoForm: {
        btitle: "",
        bsubmitter: "",
        bcategory: "技术博文",
        bcontent: "",
        bstarLevel: null,
        bRemark:"",
        StarList: [],
        bstarList: "",
        bparentId: 0,
        Father: {
          bID: 0,
          btitle: "",
        },
        imageUrlList: [],
        bstarList: "",
        bnodeLevel: 0,
      },
      blogNodeinfoForm: [],
      thisbcategory: null,
      blogFatherinfoForm: [],
      boxFather: {},
      dataform: [],
      newstarlist: [],
      bimage: "",
      images: [],
      editorOption: {},
      //表单验证
      rules: {
        btitle: [{ required: true, message: "请输入标题", trigger: "blur" }],
        bcontent: [
          { required: true, message: "请输入详细内容", trigger: "blur" },
        ],
      },
    };
  },

  //初始化
  mounted() {

    //id为空时 该页面为新增数据，id不为空时 修改,获取到该文章详细数据并赋值给组件。
   if (this.id != undefined) {
  this.buttonSubit = "确认修改";
  var para = { id: this.id };
  getBlogDeatil(para).then((res) => {
    this.infoForm = res.data.response;
    // 添加检查以确保 DisplayImageData 不为空
    if (this.infoForm.DisplayImageData) {
      this.images = this.infoForm.DisplayImageData;
    }
    if (this.infoForm.Father) {
      this.boxFather = this.infoForm.Father;
    }
    this.thisbcategory = this.infoForm.bcategory;
    this.newstarlist = this.infoForm.bstarList.split(",");
    
    // 子组件初始化
    this.initialValue = this.infoForm.bcontent;
    const childComponent = this.$refs.editorComponent;
    if (childComponent) {
      // 调用子组件的方法来获取文本框内容
      this.initialValue = this.infoForm.bcontent;
    } else {
      console.error("Failed to get reference to EditorComponent");
    }
  });
} else {
  this.buttonSubit = "新增文章";
}

    //获取一级节点（类型）
    var bcategorynull = { bcategory: null };
    GetBlogNode(bcategorynull).then((res) => {
      this.blogNodeinfoForm = res.data.response;
    });
  },

  methods: {
    ///下拉框所有节点"all""
    handleSelectStart(visible) {
  if (visible) {
    if (true) {
      var bcategorythis = { bcategory: "ALL" };
      GetBlogNode(bcategorythis).then((res) => {
        if (res.data && res.data.response) {
          this.blogFatherinfoForm = res.data.response;
        }
      }).catch((error) => {
        
      });s
    }
  }
},

methods: {

  
   // 上传成功的处理函数

  },
  handleFolderUploadSuccess(response, file, fileList) {
      console.log('文件夹上传成功');
      console.log("1")
    const folderData = response.response; // 假设服务器返回的文件夹数据
    this.initialValue = folderData; // 根据实际数据格式进行处理
    const editorComponent = this.$refs.editorComponent;
    if (editorComponent) {
      editorComponent.updateContent(this.initialValue);
    }
    },




    
    // 上传前的处理函数
    beforeFolderUpload(file) {
      console.log('文件准备上传', file);
      // 在这里可以添加一些上传前的检查或处理逻辑
      // 返回 false 可以阻止文件上传
      return true;
    },
    // 拖拽上传时的处理函数
    handleDrop(event) {
      console.log('文件夹拖拽到上传区域', event);
    },


    //子组件
    getTextFromChildComponent() {
      const childComponent = this.$refs.editorComponent;
      if (childComponent) {
        // 调用子组件的方法来获取文本框内容
        const editorContent = childComponent.hdata;
        //赋值
        this.infoForm.bcontent = editorContent;
      } else {
        console.error("Failed to get reference to EditorComponent");
      }
    },

    //所有该分类节点
    handleSelectVisibleChange(visible) {
    if (visible) {
      if (this.thisbcategory) {
        var bcategorythis = { bcategory: this.thisbcategory };
        GetBlogNode(bcategorythis).then((res) => {
          if (res.data && res.data.response) {
            this.blogFatherinfoForm = res.data.response;
          }
        }).catch((error) => {
          console.error("Failed to get blogFatherinfoForm:", error);
        });
      }
    }
  },

    // 在下拉框选项改变时更新boxFather为选中的对象
    handleSelectChange(value) {
  if (this.blogFatherinfoForm && this.blogFatherinfoForm.length > 0) {
    this.blogFatherinfoForm.forEach((item) => {
      if (item.btitle === value) {
        this.boxFather = item;
        this.infoForm.bnodeLevel = item.bnodeLevel + 1;

        //后续添加四级页的逻辑：添加时未使用合适的设计模式
        this.bottomNodeData = NaN;
        this.bottomflage=true;
      }
    });
  }
},

    //当前选择下的三级节点更新bottomNodeForm
    handleSelectVisibleChange_BottomNode(visible) {
    if (visible) {
      let para = {
        level: 3,
        category: this.boxFather.bID,
      };
      this.listLoading = true;

      GetSubBlog(para).then((res) => {
      // 获取数据后，创建一个新的对象列表，其中包含初始时序值
      this.bottomNodeForm = res.data.response;
    })
    }
  },

    // 在下拉框选项改变时更新bottomNodeData
    handleSelectChange_BottomNode(value) {
  if (this.bottomNodeForm && this.bottomNodeForm.length > 0) {
    this.bottomNodeForm.forEach((item) => {
      if (item.btitle === value) {
        // this.boxFather = item;
        this.bottomNodeData = item;
        this.infoForm.bnodeLevel = item.bnodeLevel + 1;
      }
    });
  }
},


    //图片移除
    deleteImage(index) {
      if (this.images[index].Id > 0) {
        let para = {
          id: this.images[index].Id,
        };
        DelBlogImages(para)
          .then((res) => {
            console.log(res);
            this.images.splice(index, 1); // 在异步操作完成后再移除数组元素
          })
          .catch((error) => {
            console.error("删除失败:", error);
          });
      } else {
        this.images.splice(index, 1);
      }
    },

    //图片上传及回调
    handleUploadSuccess(response, file, fileList) {
      const imagesString = response.response.replace(/,/g, ""); // 去掉逗号
      const imageUrls = imagesString.split(" ");
      imageUrls.forEach((url) => {
        // const ImagePath = "http://localhost:2364/" + url;// 本地
        // const ImagePath = "http://mingkuoapi.jieshi.cc/" + url;// 测试远程服务器
        const ImagePath = "http://123.60.82.9:9291/" + url;// 正式环境远程服务器 
        this.images.push({ ImagePath });
      });
      this.bimage = "http://123.60.82.9:9291/" + imageUrls; // 正式远程服务器
      // this.bimage = "http://mingkuoapi.jieshi.cc/" + imageUrls; // 测试远程服务器
            // this.bimage = "http://localhost:2364/" + imageUrls; // 本地

    },

    // 在上传之前的处理函数，可以做一些限制或者处理文件的操作
    beforeUpload(file) {
      // 在上传之前的处理函数，可以做一些限制或者处理文件的操作
      // 返回 false 可以阻止上传
      // 返回 true 或者不返回任何值都将继续上传
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
        return false;
      }
      
      return true;
    },

    //提交
    onSubmit() {
      //this.$refs.infoForm.validate，这是表单验证
      
      this.submitting = true;  //按钮锁定

      this.$refs.infoForm.validate((valid) => {
        ///入参数据赋值
        if (valid) {
          if(this.infoForm.bnodeLevel>=4&&this.bottomNodeData.bID!=null){
            this.infoForm.Father = this.bottomNodeData;
          }else{
            this.infoForm.Father = this.boxFather;
          }

          this.infoForm.bparentId = this.infoForm.Father.bID;
          if (this.infoForm.StarList.length == 0) {
            this.infoForm.StarList = null;
          }
          this.infoForm.bcategory = this.thisbcategory;
          this.infoForm.imageUrlList = this.images
            .filter((image) => image.Id == null)
            .map((image) => image.ImagePath);
          this.infoForm.bstarList = this.newstarlist
            .map((item) => item)
            .join(",");
          this.getTextFromChildComponent();
          if(this.bnodeLevel==1){this.infoForm.bcategory = this.btitle;};
          var postPara = this.infoForm;

        //  this.id != undefined
        }
        //有id时 调用修改接口
        if(this.id != undefined){
            editBlog(postPara).then((res) => {
            if (res.data.success) {
              this.$notify({
                type: "success",
                message: "修改成功!",
                duration: 3000,
              });
              this.$router.replace(`/Blog/Blogs`);
            } else {
              this.submitting = false;
              var errorMsg = res.data.msg;
              this.$message({
                type: "error",
                message: errorMsg,
                showClose: true,
              });
            }
          });
        }else{
          addBlog(postPara).then((res) => {
            if (res.data.success) {
              this.$notify({
                type: "success",
                message: "修改成功!",
                duration: 3000,
              });
              this.$router.replace(`/Blog/Blogs`);
            } else {
              this.submitting = false;
              var errorMsg = res.data.msg;
              this.$message({
                type: "error",
                message: errorMsg,
                showClose: true,
              });
            }
          });
        }
      });
      this.submitting = false;
    },
  },
  components: {
    //使用编辑器
    EditorComponent,
  },
};
</script>

<style>
.warp {
  background: #fff;
  padding-top: 20px;
  width: 90%;
  margin: 0 auto;
}
.ql-container.ql-snow,
.ql-editor.ql-blank {
  min-height: 500px !important;
}
.upload-list {
  display: flex;
  flex-wrap: wrap;
}
.image-item {
  position: relative;
  margin-right: 10px;
  margin-bottom: 10px;
}
.avatar {
  width: 100px;
  height: 100px;
}
.delete-icon {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 20px;
  color: red;
  cursor: pointer;
}
</style>
